package com.franklin.ideaplugin.mybatisrunner.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.franklin.tool.common.utils.ClassUtils;
import com.google.common.collect.Sets;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.search.FilenameIndex;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;

import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author ex_yejh16
 * @since 2025/03/25 16:32
 */
public class MapperUtils {

    public static List<XmlFile> findMapper(Module module, String className) {
        GlobalSearchScope searchScope = GlobalSearchScope.moduleWithDependenciesScope(module);

        String simpleClassName = ClassUtils.getSimpleClassName(className);
        Collection<VirtualFile> xmlFiles = FilenameIndex.getAllFilesByExt(module.getProject(), "xml",searchScope);
        return filterMapperFile(module, xmlFiles, className);
    }

    private static List<XmlFile> filterMapperFile(Module module,Collection<VirtualFile> xmlFiles, String className) {
        PsiManager psiManager = PsiManager.getInstance(module.getProject());
        List<XmlFile> mapperFileList = xmlFiles.stream()
                .map(psiManager::findFile)
                .filter(Objects::nonNull)
                .filter(psiFile -> psiFile instanceof XmlFile)
                .map(XmlFile.class::cast)
                .filter(xmlFile -> {
                    XmlTag rootTag = xmlFile.getRootTag();
                    if (Objects.isNull(rootTag)) {
                        return false;
                    }
                    if (!rootTag.getName().equals("mapper")) {
                        return false;
                    }
                    String namespace = XmlUtils.getAttributeValue(rootTag, "namespace");
                    return StrUtil.equals(namespace, className);
                })
                .collect(Collectors.toList());
        return mapperFileList;
    }

}
